package com.example.java_chatroom.component;

/**
 * @author Q
 * @create 2025-07-08-10:55
 */

import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import java.util.concurrent.ConcurrentHashMap;

/**
 * 通过这个类维护用户在线状态（userId和WebSocketSession之间的映射关系）
 */
@Component
public class OnlineUserManger {
    private ConcurrentHashMap<Integer,WebSocketSession> sessions = new ConcurrentHashMap<>();

    //1.用户上线，插入键值对
    public void online(int userId,WebSocketSession session) {
        if(sessions.get(userId) != null) {
            //避免多开情况
            System.out.println("[" + userId +"] 已经被登录了，登录失败!");
            return;
        }
        sessions.put(userId,session);
        System.out.println("[" + userId +"] 上线!");
    }
    //2.用户下线，删除键值对
    public void offline(int userId,WebSocketSession session) {
        WebSocketSession existSession = sessions.get(userId);
        if(existSession == session) {
            sessions.remove(userId);
            System.out.println("[" + userId +"] 下线!");
        }
    }
        //3.根据userId，获取WebSocketSession
    public WebSocketSession getSession(int userId) {
        return sessions.get(userId);
    }
}
